package com.example.neartweet;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.neartweet.ComService.LB;

public class NearTweet extends ListActivity {

	private EditText textField;
	private Button button;
	private static List<TweetItem> tweetList;
	private TweetAdapter simpleAdapter;
	private static String userName = "Default User";
	private boolean location = false;
	
	ComService serv;
	boolean isBound = false;
	boolean isRegistered = false;          

	private ServiceConnection mConnection;
	protected double x;
	protected double y;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_near_tweet);
		textField = (EditText) findViewById(R.id.editText1);
		button = (Button) findViewById(R.id.send);
		tweetList = new ArrayList<TweetItem>();
		simpleAdapter = new TweetAdapter(this, tweetList);
		
		mMessageReceiver = new BroadcastReceiver() {
		    @Override
		    public void onReceive(Context context, Intent intent) {
		        String str = intent.getStringExtra("msg");
		        Toast toast = Toast.makeText(NearTweet.this, str, Toast.LENGTH_LONG);
				toast.show();
		        String msgparts[] = str.split(":");
		        if (str.startsWith("To:")){
		        	if (msgparts.length == 6) {
			        	addTweet(msgparts[2], msgparts[3], Double.parseDouble(msgparts[4]), Double.parseDouble(msgparts[5]));
			        } else if (msgparts.length == 4) {
			        	addTweet(msgparts[2], msgparts[3]);
			        }
		        } else {
		        	if (msgparts.length == 4) {
		        		addTweet(msgparts[0], msgparts[1], Double.parseDouble(msgparts[2]), Double.parseDouble(msgparts[3]));
		        	} else if (msgparts.length == 2) {
		        		addTweet(msgparts[0], msgparts[1]);
		        	}
		        }
		        simpleAdapter.notifyDataSetChanged();
		    }
		};

		final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		Criteria crit = new Criteria();
		final String providers = locationManager.getBestProvider(crit, false);
		Location loc = locationManager.getLastKnownLocation(providers);
		if (loc != null) {
			
			x = loc.getLatitude();
			y = loc.getLongitude();
			
		}
		
		LocationListener locationListener = new LocationListener() {
		    public void onLocationChanged(Location location) {
		    	
		    	Location loc = locationManager.getLastKnownLocation(providers);
				if (loc != null) {
					
					x = loc.getLatitude();
					y = loc.getLongitude();
					
				}
				
		    }

		    public void onStatusChanged(String provider, int status, Bundle extras) {}

		    public void onProviderEnabled(String provider) {}

		    public void onProviderDisabled(String provider) {}
		  };

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
		
		mConnection = new ServiceConnection() {
			public void onServiceConnected(ComponentName className,
					IBinder service) {
				LB binder = (LB) service;
				serv = binder.getService();
				isBound = true;
				regService();
			}
			public void onServiceDisconnected(ComponentName className) {
				isBound = false;
		    }
		}; 

		setListAdapter(simpleAdapter);
		registerForContextMenu(getListView());
		
		textField.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {

				Boolean canSend = textField.getText().toString().length() > 0;
				button.setEnabled(canSend);
				
			}
		});
		
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Editable tweet = textField.getText();
				String msg;
				
				if(location){
					msg = userName + ":" + tweet.toString() + ":" + x + ":" + y;
					addTweet(userName, tweet.toString(), x, y);
				} else {
					msg = userName + ":" + tweet.toString();
					addTweet(tweet.toString());
				}
				simpleAdapter.notifyDataSetChanged();
				textField.setText("");
				
				String str = serv.receiveMessages(msg);
				Toast toast = Toast.makeText(NearTweet.this, str, Toast.LENGTH_LONG);
				toast.show();
			}
		});
				
		LocalBroadcastManager.getInstance(this).registerReceiver(
	            mMessageReceiver, new IntentFilter("message"));
		
		loadPrefs();
		
		init();
		
		initService();
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		SharedPreferences sharedPrefs = getSharedPreferences(
		        getString(R.string.preference_file_key),MODE_PRIVATE);
		int state = sharedPrefs.getInt("state", -1);
		Log.i("state", Integer.toString(state));
		if (state == 0)
			loadPrefs();
		if (state == 1) {
			String ban = sharedPrefs.getString("ban", "");
			serv.ban(userName, ban);
		}
		/*if (state == 2) {
			String tweet = sharedPrefs.getString("tweet", "");
			String to = sharedPrefs.getString("TO", "");
			sendMessageFromCompose(tweet, to);
		}*/
		SharedPreferences.Editor editor = sharedPrefs.edit();
		editor.putInt("state", -1);
		editor.commit();
	}
	
	private void sendMessageFromCompose(String tweet, String to) {
		String msg = "";
		if (!to.equals("")) {
			msg += "To:" + to + ":";
		}
		if(location){
			msg += userName + ":" + tweet + ":" + x + ":" + y;
			addTweet(userName, tweet, x, y);
		} else {
			msg += userName + ":" + tweet;
			addTweet(tweet);
		}
		simpleAdapter.notifyDataSetChanged();
		serv.receiveMessages(msg);
		serv.flush();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		serv.unRegister(userName);
		LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
		serv.stopSelf();
	}
	
	private void loadPrefs() {
		
		SharedPreferences sharedPrefs = getSharedPreferences(
		        getString(R.string.preference_file_key),MODE_PRIVATE);
		String uN = sharedPrefs.getString("usr", "");
		if (uN != "") {
			userName = uN;
			if (isBound) {
				serv.unRegister(userName);
				LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
				LocalBroadcastManager.getInstance(this).registerReceiver(
			            mMessageReceiver, new IntentFilter("speedExceeded"));
			}
		}
	}
	
	public void ban(String from, String to) {
		serv.ban(from, to);
	}
	
	private void initService() {
		Intent intent = new Intent(this, ComService.class);
		startService(intent);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}
	
	private void regService() {
		if (!isRegistered) {
			serv.register(userName);
			String str = serv.listen();
			isRegistered = true;
			Toast toast = Toast.makeText(NearTweet.this, str, Toast.LENGTH_LONG);
			toast.show();
		}
	}

	private BroadcastReceiver mMessageReceiver;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.action_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		SharedPreferences sharedPrefs = getSharedPreferences(
		        getString(R.string.preference_file_key),MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPrefs.edit();
		switch (item.getItemId()) {
		case R.id.action_settings:
			intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			break;
		case R.id.gps:
			if(location) {
				item.setIcon(R.drawable.gps_off);
				location = false;
				
				editor.putInt("gps", 0);
				editor.commit();
			} else {
				item.setIcon(R.drawable.gps_on);
				location = true;
				
				editor.putInt("gps", 1);
				editor.commit();
			}
			break;
		case R.id.poll:
			intent = new Intent(this, PollActivity.class);
			startActivity(intent);
			break;
		case R.id.compose:
			intent = new Intent(this, ComposeActivity.class);
			startActivity(intent);
			break;
		default:
			
		}
		return super.onOptionsItemSelected(item);
	}

	private void init() {
		// TODO iniciar a lista, ir buscar ao servidor
		tweetList.add(createTweet("tweet", "Ol�!", 38.737113, -9.303102));
	}

	private static void addTweet(String msg) {
		// TODO iniciar a lista, ir buscar ao servidor
		if (tweetList.size() == 50)
			tweetList.remove(tweetList.size() - 1);
		tweetList.add(0, createTweet(userName, msg));
	}
	
	private static void addTweet(String username, String msg) {
		// TODO iniciar a lista, ir buscar ao servidor
		if (tweetList.size() == 50)
			tweetList.remove(tweetList.size() - 1);
		tweetList.add(0, createTweet(username, msg));
	}
	
	private static void addTweet(String username, String msg, Double lat, Double lon) {
		// TODO iniciar a lista, ir buscar ao servidor
		if (tweetList.size() == 50)
			tweetList.remove(tweetList.size() - 1);
		tweetList.add(0, createTweet(username, msg, lat, lon));
	}

	private static TweetItem createTweet(String user, String msg) {
		return new TweetItem(user, msg);
	}
	
	private static TweetItem createTweet(String user, String msg, Double lat, Double lon) {
		return new TweetItem(user, msg, lat, lon);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu context, View view, ContextMenuInfo info){
		super.onCreateContextMenu(context, view, info);
		MenuInflater menu = getMenuInflater();
		menu.inflate(R.menu.menu_tweet, context); 
	}
	
	public boolean onContextItemSelected(MenuItem item){

		switch(item.getItemId()){
		case R.id.c_reply:
			//TODO
			return true;
		case R.id.c_retweet:
			//TODO
			return true;
		case R.id.c_flag:
			//TODO
			return true;
		case R.id.c_share:
			//TODO
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	
}
